package cn.imvc.app.controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.sd4324530.fastweixin.api.MenuAPI;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.entity.Menu;
import com.github.sd4324530.fastweixin.api.entity.MenuButton;
import com.github.sd4324530.fastweixin.api.enums.MenuType;
import com.github.sd4324530.fastweixin.api.enums.ResultType;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.message.BaseMsg;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.github.sd4324530.fastweixin.message.req.BaseEvent;
import com.github.sd4324530.fastweixin.message.req.QrCodeEvent;
import com.github.sd4324530.fastweixin.servlet.WeixinSupport;

import cn.imvc.app.entities.Dealer;
import cn.imvc.app.entities.Member;
import cn.imvc.app.models.DealerModel;
import cn.imvc.app.models.MemberModel;
import cn.imvc.core.HttpContext;
import cn.imvc.core.ICache;
import cn.imvc.core.Render;
import cn.imvc.util.Wechat;
@Controller
@RestController
@RequestMapping("/weixin.html")
public class WeixinControllerImpl extends WeixinSupport implements WeixinController {
	
	private Logger logger = Logger.getLogger(WeixinControllerImpl.class);

	@Autowired
	private Wechat wechat;
	
	@Autowired
	ICache cache;
	
	@Autowired
	DealerModel dealerModel;
	@Autowired
	MemberModel memberModel;
	
	

	@Override
	protected String getToken() {
		return wechat.getWechatToken();
	}

	// 用户关注执行方法
	@Override
	protected BaseMsg handleSubscribe(BaseEvent event) {
		//https://mp.weixin.qq.com/wiki/7/9f89d962eba4c5924ed95b513ba69d9b.html 微信文档
		UserAPI userApi = new UserAPI(wechat.getApiConfig());

		GetUserInfoResponse user = userApi.getUserInfo(event.getFromUserName());
		if (event instanceof QrCodeEvent) {
			QrCodeEvent qrCodeEvent = (QrCodeEvent) event;
			String openId=qrCodeEvent.getFromUserName();
			String key=qrCodeEvent.getEventKey();
			String[] s=key.split("_");
			Integer num=Integer.parseInt(s[1]);
			Dealer dealer=null;
			if(num>100000){
				dealer=dealerModel.get(Integer.parseInt(s[1])-100000);
			}else{
				dealer=dealerModel.findByWxqrid(Integer.parseInt(s[1]));
			}
			if (dealer!=null){
				cache.put("SCAN", openId, dealer.getMember());
				logger.info("微信扫码：openid:" + openId + ",parentid:" + dealer.getMember().getId());
			} else {
				logger.info("微信扫码：openid:" + openId + ",无上线");
			}
			
		}

		String textMsg = "星昊商城欢迎您!";

		return new TextMsg(textMsg);

	}

	// 取消关注
	protected BaseMsg handleUnsubscribe(BaseEvent event) {
		//清空openID
		UserAPI userApi = new UserAPI(wechat.getApiConfig());
		GetUserInfoResponse user = userApi.getUserInfo(event.getFromUserName());
		if(user!=null){
			Member member = memberModel.findByUnionid(user.getUnionid());
			if(member!=null){
				member.setWxOpenid(null);
				memberModel.save(member);
			}
		}
		return null;
	}

	// 用户扫描二维码执行方法
	protected BaseMsg handleQrCodeEvent(QrCodeEvent event) {

		return null;
	}
	
	
    /**
     * 绑定微信服务器
     *
     * @param request 请求
     * @return 响应内容
     */
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    protected final String bind(HttpServletRequest request) {
    
        if (isLegal(request)) {
            //绑定微信服务器成功
            return Render.text(request.getParameter("echostr"));
        } else {
            //绑定微信服务器失败
            return Render.text(request.getParameter("echostr"));
        }
    }

    /**
     * 微信消息交互处理
     *
     * @param request http 请求对象
     * @param response http 响应对象
     * @throws ServletException 异常
     * @throws IOException      IO异常
     */
    @RequestMapping(method = RequestMethod.POST)
    protected final void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (isLegal(request)) {
            String result = processRequest(request);
            //设置正确的 content-type 以防止中文乱码
            response.setContentType("text/xml;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(result);
            writer.close();
        }
    }

}
